package com.opencv.controller;

import com.opencv.domain.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.TimeUnit;

/**
 * @author qz.wu
 * @date 2021/12/28 14:07
 * @descriptions 绑定任务
 */
@RestController
@Api(tags = "绑定任务")
@RequestMapping("/bind/task")
public class BindTaskController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BindTaskController.class);

    /**
     * 连接超时返回的结果
     */
    private static final ResponseMsg<Boolean> TIME_OUT_RESULT = new ResponseMsg(-1, "超时", null, null);

    /**
     * 超时时间：1分钟
     */
    private static final long OUT_OF_TIME = 60000L;

    @GetMapping("/result")
    @ApiOperation("获取绑定任务的结果")
    public DeferredResult<ResponseMsg<Boolean>> getBindTaskResult(@RequestParam("taskId") String taskId) throws InterruptedException {
        DeferredResult<ResponseMsg<Boolean>> result = new DeferredResult<>(OUT_OF_TIME, TIME_OUT_RESULT);
        result.onTimeout(() -> {
            LOGGER.info("绑定任务结果调用超时");
        });

        result.onCompletion(() -> {
            LOGGER.info("绑定任务结果调用完成");
        });

        while (true) {
            if ("123456".equals(taskId)) {
                result.setResult(ResponseMsg.success(Boolean.TRUE));
                break;
            }
            // 模拟长轮询一直查询结果，未返回数据，直到接口超时（2分钟）
        }
        return result;
    }

    @GetMapping("/result/next")
    @ApiOperation("获取绑定任务的结果(next)")
    public ResponseMsg<Boolean> getBindTaskResultNext(@RequestParam("taskId") String taskId) throws InterruptedException {

        Boolean result = Boolean.FALSE;

        // 保持请求连接，2分钟
        for (int i = 0; i < 120; i++) {
            if ("123456".equals(taskId)) {
                result = Boolean.TRUE;
                break;
            }
            TimeUnit.SECONDS.sleep(1L);
        }
        return ResponseMsg.success(result);
    }

}
